package com.qst.yunpan.controller.customer;

import com.qst.yunpan.entity.FileCustom;
import com.qst.yunpan.entity.RecycleFile;
import com.qst.yunpan.entity.Result;
import com.qst.yunpan.entity.SummaryFile;
import com.qst.yunpan.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileService fileService;

    //获取文件
    @RequestMapping("/getFiles.action")
    public @ResponseBody Result<List<FileCustom>> getFiles(String path,HttpServletRequest request) {
        String realPath = fileService.getFilePath(request, path);
        List<FileCustom> listFile = fileService.listFile(realPath);
        Result<List<FileCustom>> result = new Result<List<FileCustom>>(325, true, "获取成功");
        result.setData(listFile);
        return result;
    }

    //文件上传
    @RequestMapping("/upload.action")
    public @ResponseBody Result<String> upload(@RequestParam("files")MultipartFile[] files,HttpServletRequest request, String currentPath){
        try {
            fileService.uploadFilePath(request,files,currentPath);
        } catch (Exception e) {
            return new Result<>(301,false,"上传失败");
        }
        return new Result<>(305,true,"上传成功");
    }

    //文件下载
    @RequestMapping("/download.action")
    public ResponseEntity<byte[]> download(HttpServletRequest request,String currentPath, String[] downPath, String username) {
        try {
            String down = request.getParameter("downPath");
            File downloadFile = fileService.downPackage(request, currentPath,downPath, username);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            String fileName = new String(downloadFile.getName().getBytes("utf-8"), "iso-8859-1");
            headers.setContentDispositionFormData("attachment", fileName);
            byte[] fileToByteArray = org.apache.commons.io.FileUtils.readFileToByteArray(downloadFile);
            fileService.deleteDownPackage(downloadFile);
            return new ResponseEntity<byte[]>(fileToByteArray, headers,HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查找文件（模糊查询）
     *
     * @param reg 要查找的文件名
     * @param currentPath 当面路径
     * @param regType 查找文件类型
     * @return Json对象
     */
    @RequestMapping("/searchFile.action")
    public @ResponseBody Result<List<FileCustom>> searchFile(HttpServletRequest request,String reg, String currentPath, String regType) {
        try {
            List<FileCustom> searchFile = fileService.searchFile(request, currentPath,reg, regType);
            Result<List<FileCustom>> result = new Result<>(376, true, "查找成功");
            result.setData(searchFile);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(371, false, "查找失败");
        }
    }


    /**
     * 打开文件
     */
    @RequestMapping("/openFile.action")
    public void openFile(HttpServletResponse response,HttpServletRequest request, String currentPath, String fileName, String fileType) {
        try {
            fileService.respFile(response, request, currentPath, fileName, fileType);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开文档
     *
     * @param currentPath 当面路径
     * @param fileName 文件名
     * @param fileType 文件类型
     * @return Json对象（文件Id）
     */
    @RequestMapping("/openOffice.action")
    public @ResponseBody Result<String> openOffice(HttpServletRequest request,String currentPath, String fileName, String fileType) {
        try {
            String openOffice = fileService.openOffice(request, currentPath,fileName);
            if (openOffice != null) {
                Result<String> result = new Result<>(505, true, "打开成功");
                result.setData(openOffice);
                return result;
            }
            return new Result<>(501, false, "打开失败");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(501, false, "打开失败");
        }
    }


    //播放音频
    @RequestMapping("/openAudioPage.action")
    public String openAudioPage(Model model, String currentPath, String fileName) {
        model.addAttribute("currentPath", currentPath);
        model.addAttribute("fileName", fileName);
        return "audio";
    }

    //新建文件夹
    @RequestMapping("/addDirectory.action")
    public @ResponseBody Result<String> addDirectory(HttpServletRequest request,String currentPath,String directoryName){
        try {
            fileService.addDirectory(request,currentPath,directoryName);
            return new Result<>(336,true,"添加成功");
        } catch (Exception e) {
            return new Result<>(331,false,"添加失败");
        }

    }

    /**
     * 删除文件夹
     *
     * @param currentPath 当前路径
     * @param directoryName 文件夹名
     * @return Json对象
     */
    @RequestMapping("/delDirectory.action")
    public @ResponseBody Result<String> delDirectory(HttpServletRequest request,String currentPath,String[] directoryName) {
        try {
            System.gc();
            Thread.sleep(1000);
            fileService.delDirectory(request, currentPath, directoryName);
            return new Result<>(346, true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(341, false, "删除失败");
        }
    }

    /**
     * 重命名文件夹
     *
     * @param currentPath 当前路径
     * @param srcName 源文件名
     * @param destName 目标文件名
     * @return Json对象
     */
    @RequestMapping("/renameDirectory.action")
    public @ResponseBody Result<String> renameDirectory(HttpServletRequest request,String currentPath, String srcName, String destName) {
        try {
            fileService.renameDirectory(request, currentPath, srcName, destName);
            return new Result<>(356, true, "重命名成功");
        } catch (Exception e) {
            return new Result<>(351, false, "重命名失败");
        }
    }

    @RequestMapping("/summarylist.action")
    public String summarylist(HttpServletRequest request,Model model){
        String webrootpath = fileService.getFilePath(request,"");
        int number = webrootpath.length();
        SummaryFile rootlist = fileService.summarylistFile(webrootpath,number);
        model.addAttribute("rootlist",rootlist);
        return "summarylist";
    }

    @RequestMapping("/copyDirectory.action")
    public @ResponseBody Result<String> copyDirectory(HttpServletRequest request,String currentPath,String[] directoryName,String targetdirectorypath) throws  Exception{
        try {
            fileService.copyDirectory(request,currentPath,directoryName,targetdirectorypath);
            return new Result<>(366, true, "复制成功");
        } catch (Exception e) {
            return new Result<>(361, false, "复制失败");
        }
    }

    //移动文件夹
    @RequestMapping("/moveDirectory.action")
    public @ResponseBody Result<String> moveDirectory(HttpServletRequest request,String currentPath,String[] directoryName,String targetdirectorypath) throws  Exception{
        try {
            fileService.moveDirectory(request,currentPath,directoryName,targetdirectorypath);
            return new Result<>(366, true, "移动成功");
        } catch (Exception e) {
            return new Result<>(361, false, "移动失败");
        }
    }

    //查找回收站
    @RequestMapping("/recycleFile.action")
    public String recycleFile(HttpServletRequest request){
        try {
            List<RecycleFile> findDelFile = fileService.recycleFiles(request);
            if(findDelFile != null && findDelFile.size() != 0){
                request.setAttribute("findDelFile",findDelFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "recycle";
    }

    //还原已删除的文件/文件夹
    @RequestMapping("/revertDirectory.action")
    public @ResponseBody Result<String> revertDirectory(HttpServletRequest request,int[] fileId){
        try {
            fileService.revertDirectory(request,fileId);
            return new Result<>(327, true, "还原成功");
        } catch (Exception e) {
            return new Result<>(322, false, "还原失败");
        }
    }

    //清空回收站
    @RequestMapping("/delAllRecycle.action")
    public @ResponseBody Result<String> delAllRecycle(HttpServletRequest request){
        try {
            fileService.delAllRecycle(request);
            return new Result<>(327, true, "清空成功");
        } catch (Exception e) {
            return new Result<>(322, false, "清空失败");
        }
    }

    //删除回收站单个文件
    @RequestMapping("/delRecycle.action")
    public @ResponseBody Result<String> delRecycle(HttpServletRequest request, int fileId){
        try {
            fileService.delRecycle(request,fileId);
            return new Result<>(327, true, "删除成功");
        } catch (Exception e) {
            return new Result<>(322, false, "删除失败");
        }
    }


}
